package com.song.server.config.security;

// 权限控制 - 根据请求的url分析所需要的角色

import com.song.server.entity.Menu;
import com.song.server.entity.Role;
import com.song.server.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private MenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        // 获取请求的url
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        // 获取所有的菜单列表（带角色列表）
        List<Menu> menus = menuService.getMenusWithRole();
        // 判断请求url与菜单的url是否匹配
        for (Menu menu : menus) {
            // 如果匹配，获取访问该url所需要的角色列表
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {
                String[] roleString = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                return SecurityConfig.createList(roleString);
            }
        }
        // 如果都没有匹配上，默认登录即可访问（只要拥有ROLE_LOGIN角色）
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
